import _path from 'path'
// import fs from 'fs'
// import {nativeImage} from 'electron'
// import jsPDF from 'jspdf'
// import ExcelJS from 'exceljs'
import XLSX from 'xlsx'
import fs from 'fs'

/**
 * 子线程执行的js模块，需要export一个start()方法
 * 第一个参数data，为调用传参
 * data = {
 *  filename: filename,
 *  fileList: this.fileList,
 *  userConfig: this.userConfig
 * }
 * 第二个参数sendInfo(response)是一个function，执行该函数可向主线程发送消息
 */
export function start (data, sendInfo) {
  return new Promise(async (resolve, reject) => {
    console.log('开始')
    let exportPath = data.userConfig['ExcelMerge.ExportPath']
    let filePath = _path.join(exportPath, data.filename)
    console.log('filePath: ' + filePath)
    let skipHeader = false
    for (let n = 0; n < data.fileList.length; n++) {
      let it = data.fileList[n]
      console.log('Excel: ' + it.name)
      let workBook = XLSX.readFile(it.path)
      console.log('file name: ' + it.name)
      let resultJsonArr = []
      workBook.SheetNames.forEach(sheetName => {
        console.log('sheetName: ' + sheetName)
        let workSheet = workBook.Sheets[sheetName]
        let jsonArr = XLSX.utils.sheet_to_json(workSheet)
        resultJsonArr.push(...jsonArr)
        console.log('sheet data length: ' + jsonArr.length)
      })
      console.log('file data length: ' + resultJsonArr.length)
      await add(filePath, resultJsonArr, skipHeader)
      skipHeader = true
      sendInfo && sendInfo((n + 1) / data.fileList.length)
    }
    resolve(filePath)
  })
}

function add (filePath, jsonArr, skipHeader) {
  return new Promise((resolve, reject) => {
    const resultWookSheet = XLSX.utils.json_to_sheet(jsonArr, {skipHeader: skipHeader})
    const stream = XLSX.stream.to_csv(resultWookSheet)
    const writeStream = fs.createWriteStream(filePath, {flags: 'a'})
    stream.pipe(writeStream)
    stream.on('end', () => {
      console.log('已写入数量: ' + jsonArr.length)
      resolve()
    })
  })
}
